﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Douban.Api.Templates
{
    public class TemplateLoader
    {
        private static string _templateBasePath;
        private static IDictionary<string, string> _templateCache;

        private TemplateLoader() {}

        static TemplateLoader()
        {
            Instance = new TemplateLoader();
            _templateCache = new Dictionary<string, string>();
            _templateBasePath = Assembly.GetExecutingAssembly().GetName().Name + ".Templates.{0}.xml";
        }

        public static TemplateLoader Instance { get; private set; }

        public Template Load(string templateName)
        {
            string value = null;
            Template template = null;

            if (!_templateCache.TryGetValue(templateName, out value))             
            {
                Stream templateStream = Assembly.GetExecutingAssembly()
                    .GetManifestResourceStream(string.Format(_templateBasePath, templateName));

                if (templateStream == null)
                    throw new TemplateNotFoundException(templateName + " not found");

                StreamReader reader = new StreamReader(templateStream);
                value = reader.ReadToEnd();

                reader.Close();

                _templateCache.Add(templateName, value);
            }

            return new Template(value);
        }
    }
}
